package flowcontrol.condition;

import java.util.concurrent.locks.Condition;
import java.util.concurrent.locks.ReentrantLock;

/**
 * condition基本用法
 */
public class TestCondition1 {

    private ReentrantLock lock = new ReentrantLock();
    private Condition condition = lock.newCondition();

    void method1(){
        lock.lock();
        try {
            System.out.println("条件不满足，开始 await");
            condition.await();
            System.out.println("条件满足，开始执行后续任务");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } finally {
            lock.unlock();
        }
    }

    void method2(){
        lock.lock();
        try {
            System.out.println("准备工作完成，开始唤醒其他线程");
            condition.signal();
        }finally {
            lock.unlock();
        }
    }

    public static void main(String[] args) {
        TestCondition1 condition1 = new TestCondition1();

        new Thread(() -> {
            try {
                Thread.sleep(1000);
                condition1.method2();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        }).start();

        condition1.method1();
    }
}
